import { ExplorerFunctions } from "./FileExplorerFunctions.tsx";
import { useLocation, useNavigate } from "react-router-dom";
import { invoke } from "@tauri-apps/api/core";
import { useEffect, useCallback, useState } from "react";
import { Timer } from "./Timer.tsx"
import { FileItem } from "./UserInterface.tsx";

import "./CloudFilesList.css";

export function CloudFilesList() {
    const {
        routeinforef,
        selectedFiles, setSelectedFiles,
        uploadedFileItems, setUploadedFileItems,
        isLoading, setIsLoading,
        deleteFromOSS,
        handleRowClick,
        handleRowDoubleClick,
        downloadFromOSS,
        handleCheckboxChange,
        formatFileSize,
    } = ExplorerFunctions();

    const [error, setError] = useState("");
    const location = useLocation();
    const navigate = useNavigate();

    const handleOpenCloudFilesList = useCallback(async () => {
        try{
            setIsLoading(true);
            setSelectedFiles(new Set());
            // console.log("current path", location.state.path);
            const route_info = {
                user : location.state.routeInfo.user,
                url : location.state.routeInfo.url,
            }
            routeinforef.current = route_info;
            if(route_info.user && route_info.url){
                const fileItems = await invoke<FileItem[]>("check_cloud_files", {
                    user : route_info.user,
                    mongodbUrl : route_info.url, 
                });
                for(const item of fileItems){
                    console.log("uploaded file name", item.name);
                }
                setUploadedFileItems(fileItems);
            }else{
                console.error("User and URL is not defined");
            }
        }catch(error){
            console.error("Failed to load cloud files:", error);
            setError(String(error));
        }
        setIsLoading(false);
    }, [uploadedFileItems]);

    useEffect(() => {
        handleOpenCloudFilesList();
        console.log("entered into cloud files list.");
    }, []);
    
    // 对文件进行排序：先按类型排序，再按名称排序
    const sortFiles = [...uploadedFileItems].sort((a, b) => {
        const getExtension = (name: string) => {
            const lastDotIndex = name.lastIndexOf('.');
            return lastDotIndex > 0 ? name.slice(lastDotIndex + 1).toLowerCase() : '';
        };
        const extA = getExtension(a.name);
        const extB = getExtension(b.name);
        // 不区分大小写的扩展名比较
        const typeComparison = extA.localeCompare(extB);
        // 扩展名相同则进行全名比较（不区分大小写）
        return typeComparison !== 0 ? typeComparison : 
            a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
    });
    return (
        <div className="cloud-files-list">
            <h1 id="cloudfileslistext">🤠Cloud Files List</h1>
            <div id="titletop-execptitle">
                <div id="toolsbar">
                    <button id="cloudfiles-return" 
                            onClick={() => navigate("/files", 
                            { state : {
                                 path : location.state.path,
                                 routeInfo : routeinforef.current, 
                                 oss: location.state.oss,
                                }
                            })}>
                        🔙Return
                    </button> 
                    <div className="cloudmove">
                        <button id="cloudfiles-download" 
                            onClick={downloadFromOSS}
                            disabled={
                                selectedFiles.size === 0 || isLoading}
                            >⬇Download</button>
                        <button id="cloudfiles-delete"
                            onClick={deleteFromOSS}
                            disabled={selectedFiles.size === 0 || isLoading}
                        >🗑Delete Cloud File</button>
                    </div>
                </div>
                <div id="cloud-statusbar">
                {/* 显示选中的文件数量和操作按钮 */}
                    {selectedFiles.size > 0 && (
                    <div id="cloud-selected-info">
                        Selected {selectedFiles.size} file(s)
                    </div>
                    )}
                </div>
            </div>
            {isLoading ? (
                <div id="cloud-files-loading-bar">
                    <span id="cloudfiles-loading" >🔄Loading...</span>
                    <Timer />
                </div>
            ) : error ? ( 
            <span id="error">{error}</span>
            ) : sortFiles.length === 0 ? (
                <span id="cloud-empty-dir">🈚This directory is empty</span>
            ) : (
                <table id="fileslist">
                    <colgroup>
                        <col className="select" />
                        <col className="name" />
                        <col className="time" />
                        <col className="type" />
                        <col className="size" />
                    </colgroup>
                    <thead id="fileslist-topbar">
                        <tr>
                            <th className="select">😌Select</th>
                            <th className="name">😪Name</th>
                            <th className="time">😔Latest Uploaded</th>
                            <th className="type">🤤Type</th>
                            <th className="size">😴Size</th>
                        </tr>
                    </thead>
                    <tbody id="cloudfilelist">
                        {sortFiles.map((file) => (
                            <tr key={file.path}
                                onClick={()=>handleRowClick(file)}
                                onDoubleClick={() => handleRowDoubleClick(file)}
                                className={selectedFiles.has(file.path) ? 'selected-file' : ''}
                            >
                                <td className="select">
                                    <input
                                        type="checkbox"
                                        title="select this file"
                                        checked={selectedFiles.has(file.path)}
                                        onChange={(e) => handleCheckboxChange(e, file.path)}
                                    />
                                </td> 
                                <td className="name">{file.name}</td>
                                <td className="time">{file.timestamp}</td>
                                <td className="type">{file.name.includes('.') ? 
                                    `${file.name.split('.').pop()}` : "File"}
                                </td>
                                <td className="size">{file.size ? `${formatFileSize(file.size)}` : "--"}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            )}
        </div>
    );
}

export default CloudFilesList;